'''
Author: Mr.Sen
LastEditTime: 2021-01-18 20:41:15
Description: 
Website: https://grimoire.cn
Copyright (c) Mr.Sen All rights reserved.
'''
from database.models import users, meta
from django.http import JsonResponse
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout

def loginApi(request):
    if request.method == "GET":
        return render(request, "login.html")
    
    username = request.POST.get("username")
    password = request.POST.get("password")

    user = authenticate(request,username=username,password=password)
    if user is not None:
        login(request, user)
        return JsonResponse({"status":1, "msg":"登陆成功"})
    else:
        return JsonResponse({"status":0, "msg":"密码或用户名有误，请检查后重试"})


def registerApi(request):
    if request.method == "GET":
        return render(request, "login.html")

    username = request.POST.get("username")
    password = request.POST.get("password")
    nickname = request.POST.get("nickname")

    
    if User.objects.filter(username=username).exists() or ("test" in username):
        user = authenticate(username=username, password=password)
        return JsonResponse({"status":0, "msg":"该用户名已被占用"})
        
    user = User.objects.create_user(username=username, password=password)
    user2 = users(name=username,userId=user.id, nicName=nickname)
    user.save()
    user2.save()

    meta.objects.create(name="默认分组", count=0, user=user2)

    return JsonResponse({"status":1, "msg":"注册成功"})
